import Mock from "mockjs";

const data = Mock.mock({
  // 属性 list 的值是一个数组，其中含有 1 到 10 个元素
  "list|5-10": [
    {
      // 属性 id 是一个自增数，起始值为 1，每次增 1
      "id|+1": 1,
      name: "@cname",
      age: "@integer(18, 60)",
    },
  ],
});

Mock.mock("/api/getUsers", "get", {
  code: 200,
  users: data.list,
});
// 添加用户
Mock.mock("/api/addUser", "post", (options) => {
  const newUser = JSON.parse(options.body);
  newUser.id = data.list.length + 1;
  data.list.push(newUser);
  return {
    code: 200,
    message: "添加成功",
    user: newUser,
  };
});

// 修改用户
Mock.mock(/\/api\/updateUser\/\d+/, "put", (options) => {
  const id = parseInt(options.url.match(/\/api\/updateUser\/(\d+)/)[1]);
  const updateUser = JSON.parse(options.body);
  const index = data.list.findIndex((item) => item.id === id);
  if (index !== -1) {
    data.list[index] = { ...data.list[index], ...updateUser };
    return {
      code: 200,
      message: "修改成功",
      user: data.list[index],
    };
  }
  return {
    code: 404,
    message: "用户不存在",
  };
});

// 删除用户
Mock.mock(/\/api\/deleteUser\/\d+/, "delete", (options) => {
  const id = parseInt(options.url.match(/\/api\/deleteUser\/(\d+)/)[1]);
  const index = data.list.findIndex((item) => item.id === id);
  if (index !== -1) {
    data.list.splice(index, 1);
    return {
      code: 200,
      message: "删除成功",
    };
  }
  return {
    code: 404,
    message: "用户不存在",
  };
});
